package utils

import (
	"sync"
	"time"
)

var FlowCountManager *FlowCounter

type FlowCounter struct {
	RedisFlowCountMap   map[string]*RedisFlowCountService // k= serverName
	RedisFlowCountSlice []*RedisFlowCountService
	Locker              sync.RWMutex
}

func NewFlowCounter() *FlowCounter {
	return &FlowCounter{
		RedisFlowCountMap:   map[string]*RedisFlowCountService{},
		RedisFlowCountSlice: []*RedisFlowCountService{},
		Locker:              sync.RWMutex{},
	}
}

func init() {
	FlowCountManager = NewFlowCounter()
}

//  获取redis统计器 RedisFlowCountService  统计项: 全站、服务、租户 流量
func (f *FlowCounter) GetRedisCounter(serverName string) (*RedisFlowCountService, error) {
	f.Locker.RLock() // 读锁查找
	if v, ok := f.RedisFlowCountMap[serverName]; ok {
		f.Locker.RUnlock()
		return v, nil
	}
	f.Locker.RUnlock()

	f.Locker.Lock()
	defer f.Locker.Unlock()
	if v, ok := f.RedisFlowCountMap[serverName]; ok {
		f.Locker.Unlock()
		return v, nil
	}

	redisFlowCountService := NewRedisFlowCountService(serverName, 1*time.Second)

	f.RedisFlowCountSlice = append(f.RedisFlowCountSlice, redisFlowCountService)
	f.RedisFlowCountMap[serverName] = redisFlowCountService
	return redisFlowCountService, nil
}
